import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { AdminMail } from './AdminMail';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**数据库的邮件结构属性枚举*/
export const enum E_AdminMails {
	/**邮件列表*/
	MAILS = 0,
	/**枚举数量*/
	EnumCount = 1
}


/**数据库的邮件结构*/
export class AdminMails {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_ADMIN_MAILS_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_ADMIN_MAILS_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: AdminMails[] = [];

	/**创建入口*/
	public static create(json?: string): AdminMails {
		const c = this.POOL.pop() || new AdminMails();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**邮件列表*/
	protected _mails: HashMap<number, AdminMail> = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (AdminMails.POOL.indexOf(this) === -1) {
			AdminMails.POOL.push(this);
		}
	}

	/**设置邮件列表*/
	public putMails(k: number, v: AdminMail): AdminMail {
		const ov = this._mails.put(k, v);
		return ov;
	}


	/**获取邮件列表*/
	public getMails(k: number) {
		return this._mails.get(k);
	}


	/**删除邮件列表*/
	public removeMails(k: number, autoDestroy = false): AdminMail {
		const ov = this._mails.remove(k);
		if (autoDestroy && ov) {
			ov.destroy();
		}
		return ov;
	}


	/**获取邮件列表映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getMailsKeys(): number[] {
		return this._mails.getKeys();
	}


	/**获取邮件列表映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getMailsValues(): AdminMail[] {
		return this._mails.getValues();
	}


	/**清空邮件列表映射表*/
	public clearMailsMap(autoDestroy = false): void {
		const ks = this._mails.getKeys();
		for (let i = ks.length - 1; i >= 0; i--) {
			this.removeMails(ks[i], autoDestroy);
		}
	}



	/**通过枚举获取值*/
	public getV(k: E_AdminMails): any {
		switch (k) {
			case E_AdminMails.MAILS: return this._mails;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_AdminMails, v: any): void {
		switch (k) {
			case E_AdminMails.MAILS: this._mails = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//邮件列表
		if (this._mails) {
			const list = this._mails.getValues();
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._mails.clear();
		}
		else {
			this._mails = new HashMap<number, AdminMail>();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._mails.size() > 0) {
			const ks = this._mails.getKeys();
			const vs = this._mails.getValues();
			const list: string[] = [];
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.mails = [ks, list];
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.mails) {
			const ks: number[] = json.mails[0] || (json.mails.getKeys ? json.mails.getKeys() : null);	//对象可能是json或者结构体
			const vs: string[] = json.mails[1] || (json.mails.getValues ? json.mails.getValues() : null);
			if (ks && vs && ks.length === vs.length) {
				for (let i = 0, len = vs.length; i < len; i++) {
					this._mails.put(ks[i], AdminMail.create(vs[i]));
				}
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		//邮件列表
		{
			const ks = this._mails.getKeys();
			const vs = this._mails.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				vs[i].toBytes(byte);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		//邮件列表
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = AdminMail.create();
				v.fromBytes(byte);
				this._mails.put(k, v);
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): AdminMails {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = AdminMails.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = AdminMails.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];

			//邮件列表
			if (idx === E_AdminMails.MAILS) {
				const k: number = us[i + 1];
				const ctrl: number = us[i + 2];
				if (ctrl === 0) {
					const oldv = this.removeMails(k);
					if (oldv) {
						oldv.destroy()
					}
				}
				else if (ctrl === 1) {
					const newv = AdminMail.create(us[i + 3]);
					const oldv = this.putMails(k, newv);
					if (oldv) {
						oldv.destroy()
					}
				}
				else {
					const curv = this.getMails(k);
					if (curv) {
						curv.processUpdate(us[i + 3]);
					}
					else {
						console.error('AdminMails AdminMail is not exist when update! k = ' + k);
					}
				}
				IAsync.dispatch(eventID, idx, k, ctrl);
				i += ctrl === 0 ? 3 : 4;
				continue;
			}

			console.error('[Struct Data] can not find enum in AdminMails with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: AdminMails): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];


		//邮件列表
		{
			const idx = E_AdminMails.MAILS;
			const ks1 = this._mails.getKeys();
			const ks2 = other._mails.getKeys();
			const rs = MathUtils.intersectSortedArray(ks1, ks2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getMails(k);
					const oldv = other.getMails(k);
					const ui = newv.getCompareInfo(oldv);
					if (ui && ui.length > 0) {
						updates.push(idx, k, 2, ui);
					}
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getMails(k);
					updates.push(idx, k, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(AdminMails.TOTAL_EVENT_ID, this.getV(0));
	}

}
